<template>
  <div>
      <van-field :placeholder="placeholder" :label="title" :value="picker_data.name" :is-link="isLink" :border="isBorder" :input-align="inputAlign" readonly  @click="openPicker">
          <div slot="left-icon">
              <slot name="icon"></slot>
          </div>
      </van-field>
      <van-popup v-model="visible" round position="bottom" :z-index="zIndex" @click-overlay="visible = false">
          <van-picker :columns="picker_list" :default-index="current" value-key="name" :show-toolbar="true" @confirm="getPicker" @cancel="visible = false" />
      </van-popup>
  </div>
</template>
<script>
export default {
  props:{
      isLink: {
          type: Boolean,
          default: () => {return true}
      },
      inputAlign:{
          type: String,
          default: () => 'left'
      },
      title: {
          type: String,
      },
      value: {
          type: String || Number
      },
      list: {
          type: Array
      },
      zIndex: {
          type: Number,
          default: () => 100,
      },
      placeholder: {
          type: String,
          default: () => '请选择',
      },
      isBorder: {
          type: Boolean,
          default: () => true,
      }
  },
  data(){
      return{
          visible: false,
      }
  },
  computed:{
      picker_list(){
          return this.list;
      },
      picker_data:{
          get(){
              let obj = this.list.find(item => {
                  return item.id == this.value;
              });
              if(obj){
                  return obj;
              }else{
                  return {};
              }
          },
          set(newVal){
              console.log(newVal);
          }
      },
      current:{
          get(){
              let i = 0;
              this.list.forEach((item,index) => {
                  if(item.id == this.value){
                      i = index;
                  }
              })
              return i;
          },
          set(newVal){
              console.log(newVal);
          }
      }
  },
  methods:{
      openPicker(){
          if(this.picker_list.length > 0){
              this.visible = true;
              console.log('hello')
          }else{
              this.$emit('beforeOpen');
          }
          
      },
      getPicker(e){
          this.picker_data.id = e.id;
          this.picker_data.name = e.name;
          this.$emit('update:value', e.id);
          this.$emit('confirm', e);
          this.visible = false;
      }
  }
}
</script>